<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-09-25
 * Time: 16:06
 */

namespace App\Models;

use Illuminate\Support\Facades\Cache;

/**
 * Class Order
 * @package App\Models
 */
class Order extends BaseModel
{
    /**
     * 与模型关联的数据表
     *
     * @var string
     */
    protected $table = 'orders';

    /**
     * 主键
     * @var string
     */
    protected $primaryKey = 'orderId';

    /**
     * 需要被转换成日期的属性。
     *
     * @var array
     */
    protected $dates = ['created_at', 'updated_at', 'paid_time', 'distribution_time'];

    /**
     * @var array
     */
    protected $guarded = ['orderId'];

    /**
     * @var array
     */
    protected $hidden = ['deleted_at'];

    /**
     * @var bool
     */
    public $timestamps = false;

    /**
     * @var array
     */
    protected $appends = [];

    /**
     * 发货状态
     * @var array
     */
    public static $shipStatusMap = [
        SHIP_STATUS_PENDING   => '待发货',
        SHIP_STATUS_DELIVERED => '已发货待收货',
        SHIP_STATUS_RECEIVED  => '已完成',
    ];

    /**
     * 监听模型
     */
    protected static function boot(){
        parent::boot();

        // 监听模型创建事件，在写入数据库之前触发
        static::creating(function ($model) {

            // 如果模型的 no 字段为空
            if ( !$model->no ) {

                // 调用 findAvailableNo 生成订单流水号
                $model->no = static::findAvailableNo();

                // 如果生成失败，则终止创建订单
                if (!$model->no) {
                    return false;
                }
            }
        });
    }

    /**
     * 生成订单号
     * 订单号规则, 年月日时分秒 + 6位数
     * @return bool|string
     */
    public static function findAvailableNo(){
        $time = date('YmdHis',time());
        $number = mt_rand(100000, 999999);
        $value = $time . $number;
        $cacheKey = 'order_number_'. $time;

        // 放redis 查看是否有重复
        if($cache = Cache::get($cacheKey, [])){
            if(in_array($number, $cache)){
                return self::findAvailableNo();
            }
        }
        array_push($cache, $number);
        Cache::put($cacheKey, $cache, 1);
        return  $value;
    }

    /**
     * 订单详情
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function items(){
        return $this->hasMany(OrderItems::class, 'orderId', 'orderId');
    }

    /**
     * 下单用户
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'userId', 'id');
    }

    /**
     * 申请成为寄拍订单
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function mailing(){
        return $this->hasOne(UserMailing::class, 'orderId', 'orderId');
    }

    /**
     * 用户收货地址
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function userAddress(){
        return $this->hasMany(UserAddress::class, 'userId', 'userId');
    }

    /**
     * 暂定十位数字,拼接上类型
     * @param $payType
     * @return string
     * @throws \Exception
     */
    public static function orderNo($payType){

        //时间+随机数字组成
        $no = date("YmdHis") .$payType. random_int(000, 999) . random_int(00, 99);

        //验证唯一性
        if ( self::checkOriginalNo($no) ) {
            return self::orderNo($payType);
        }

        return $no;
    }

    /**
     * 验证单号唯一性
     * @param $no
     * @return mixed
     */
    public static function checkOriginalNo($no)
    {
        return static::where('no', $no)->exists();
    }


}
